package com.hopedove.callsystem.activity.call;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.callsystem.R;
import com.hopedove.callsystem.databinding.ActivitySavestartBinding;
import com.hopedove.callsystem.domain.net.MainStartAffirm;
import com.hopedove.callsystem.domain.net.QueryDictData;
import com.hopedove.callsystem.domain.net.QueryMachineNoInfo;
import com.hopedove.callsystem.domain.net.QueryMonadNoInfo;
import com.hopedove.callsystem.entity.SJZDEntity;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.utils.ToastUtil;
import com.hopedove.view.SimpleDialog;
import com.hopedove.view.TipsDialogFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class SaveStartActivity extends BaseActivity implements OnClickListener {
    // 获取任务类型的数据字典id
    private static final String SJZDID_TASKLX = "BQTASKLX";

    /** 存储任务类型的颜色 **/
    // private List<Drawable> taskBg = new ArrayList();
    /**
     * 任务类型集合
     **/
    private List<SJZDEntity> mTasks = new ArrayList();
    /**
     * 任务类型集合
     **/
    private List<SJZDEntity> mTasksBq = new ArrayList();
    /**
     * 任务类型集合
     **/
    private List<SJZDEntity> mTasksDc = new ArrayList();
    /**
     * 任务类型
     **/
    private String mTaskLx = "";

    /**
     * 三联单号
     **/
    private String mMonadNo = "";
    /**
     * 车号
     **/
    private String mMachineNo = "";
    /**
     * 保全工工号
     **/
    private String mBqNo = "";
    /**
     * 三联单号是否正确
     **/
    private boolean isMonadNoCorrect = false;

    private String mHJLX = "";

    /**
     * 任务完成状态 记录三联单号状态 1：呼叫中 2:保全中
     ***/
    private String mState = "";
    private String mMainid = "";
    private TipsDialogFragment tipDialog;
    private static final String EXTRA_MONADNO = "monadNo";
    private static final String EXTRA_MACHINENO = "machineNo";
    private static final String EXTRA_TASKLX = "taskLx";
    private static final String EXTRA_STATE = "state";
    private static final String EXTRA_HJLX = "HJLX";

    public static void actionStart(Context context, String monadNo, String machineNo, String taskLx, String state,
                                   String HJLX) {
        Intent intent = new Intent(context, SaveStartActivity.class);
        intent.putExtra(EXTRA_MONADNO, monadNo);
        intent.putExtra(EXTRA_MACHINENO, machineNo);
        intent.putExtra(EXTRA_TASKLX, taskLx);
        intent.putExtra(EXTRA_STATE, state);
        intent.putExtra(EXTRA_HJLX, HJLX);
        context.startActivity(intent);
    }

    ActivitySavestartBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySavestartBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initViewAndEvent();
        initData();
    }

    private void initViewAndEvent() {
        Intent intent = getIntent();
        if (intent != null) {
            mMonadNo = intent.getExtras().getString(EXTRA_MONADNO);
            mMachineNo = intent.getExtras().getString(EXTRA_MACHINENO);
            mTaskLx = intent.getExtras().getString(EXTRA_TASKLX);
            mState = intent.getExtras().getString(EXTRA_STATE);
            mHJLX = intent.getExtras().getString(EXTRA_HJLX);
            if (!TextUtils.isEmpty(mMonadNo)) {
                isMonadNoCorrect = true;
            }
        }


        binding.monadNoEt.setText(mMonadNo);
        binding.machineNoEt.setText(mMachineNo);

        binding.okBtn.setOnClickListener(this);
        binding.cancelBtn.setOnClickListener(this);

        binding.monadNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_UP) {
                String monadNo = binding.monadNoEt.getText().toString().trim();
                String machineNo = "";
                if (monadNo.length() >= 4) {
                    machineNo = monadNo.substring(0, 4);
                    binding.machineNoEt.removeTextChangedListener(machineNoEtWatcher);
                    binding.machineNoEt.setText(machineNo);
                    binding.machineNoEt.addTextChangedListener(machineNoEtWatcher);
                    queryMonadNoInfo(monadNo);

                } else {
                    SimpleDialog.show(SaveStartActivity.this, "三联单号格式不正确，请重新扫描！");
                }

                return true;
            }
            return false;
        });
        monadNoEtWatcher = new MyTextWatcher(binding.monadNoEt);
        binding.monadNoEt.addTextChangedListener(monadNoEtWatcher);

        machineNoEtWatcher = new MyTextWatcher(binding.machineNoEt);
        binding.machineNoEt.addTextChangedListener(machineNoEtWatcher);

        binding.machineNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_UP) {
                String machineNo = binding.machineNoEt.getText().toString().trim();
                if (machineNo.length() == 4) {
                    queryMachineNoInfo(machineNo);
                } else {
                    SimpleDialog.show(SaveStartActivity.this, "车号不正确，请重新扫描！");
                }
                return true;
            }
            return false;
        });

    }

    private void initData() {
        querySJZD(SJZDID_TASKLX);// 任务类型字典项
    }


    MyTextWatcher monadNoEtWatcher;
    MyTextWatcher machineNoEtWatcher;


    private class MyTextWatcher implements TextWatcher {

        private EditText mEditText;

        public MyTextWatcher(EditText editText) {
            this.mEditText = editText;
        }

        @Override
        public void afterTextChanged(Editable s) {

            if (mEditText.getId() == R.id.monadNoEt) {
                binding.machineNoEt.removeTextChangedListener(machineNoEtWatcher);
                binding.machineNoEt.setText("");
                binding.machineNoEt.addTextChangedListener(machineNoEtWatcher);
                binding.taskLayout.removeAllViews();
                isMonadNoCorrect = false;// 三联号改变了需要重新校验
                binding.bqNoEt.setEnabled(true);
                binding.bqNoEt.setText("");
            } else if (mEditText.getId() == R.id.machineNoEt) {
                binding.monadNoEt.removeTextChangedListener(monadNoEtWatcher);
                binding.monadNoEt.setText("");
                binding.monadNoEt.addTextChangedListener(monadNoEtWatcher);
                binding.taskLayout.removeAllViews();
                isMonadNoCorrect = false;// 三联号改变了需要重新校验
                binding.bqNoEt.setEnabled(true);
                binding.bqNoEt.setText("");
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

    }


    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.okBtn) {
            mMonadNo = binding.monadNoEt.getText().toString().trim();
            mMachineNo = binding.machineNoEt.getText().toString().trim();
            mBqNo = binding.bqNoEt.getText().toString().trim().toUpperCase();// 转大写

            if (TextUtils.isEmpty(mMonadNo)) {
                SimpleDialog.show(this, "三联单号不能为空，请重新扫描！");
                return;
            } else if (TextUtils.isEmpty(mMachineNo)) {
                SimpleDialog.show(this, "车号不能为空，请重新输入！");
                return;
            } else if (TextUtils.isEmpty(mTaskLx)) {
                SimpleDialog.show(this, "请选择任务类型！");
                return;
            } else if (TextUtils.isEmpty(mBqNo)) {
                SimpleDialog.show(this, "保全工工号不能为空，请重新输入！");
                return;
            }
            saveStart(mMonadNo, mMachineNo, mTaskLx, mBqNo, mHJLX, mState, mMainid);
        } else if (id == R.id.cancelBtn) {
            finish();
        }
    }

    /**
     * 呼叫信息查询
     */
    private void queryMonadNoInfo(String monadNo) {
        showWait();

        Communication.asyncRequest(new QueryMonadNoInfo(monadNo), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    JSONObject data = jsonObj.optJSONObject("DATA");
                    if (data != null) {
                        // 存在呼叫信息，则是默认挡车工呼叫
                        binding.machineNoEt.removeTextChangedListener(machineNoEtWatcher);
                        binding.monadNoEt.removeTextChangedListener(monadNoEtWatcher);
                        mHJLX = "1";
                        isMonadNoCorrect = true;
                        mMonadNo = data.optString("MONADNO");
                        mMachineNo = data.optString("MACHINENO");
                        mTaskLx = data.optString("TASKLX");
                        mState = data.optString("STATE");
                        mBqNo = data.optString("BQNO");
                        mMainid = data.optString("MAINID");
                        binding.machineNoEt.setText(mMachineNo);
                        binding.machineNoEt.addTextChangedListener(machineNoEtWatcher);
                        binding.monadNoEt.addTextChangedListener(monadNoEtWatcher);
                        binding.bqNoEt.requestFocus();
                        if (!"null".equals(mBqNo)) {
                            binding.bqNoEt.setText(mBqNo);
                        }

                        initAllButton();
                        //如果是2   任务类型能改，保全工工号置灰
                        if ("2".equals(mState)) {
                            binding.bqNoEt.setEnabled(false);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else if (r instanceof ErrResponse) {
                ToastUtil.longToast(this, ((ErrResponse) r).getErrText());
                mHJLX = "2";
                initAllButton();
            }

        });
    }

    /**
     * 开始保全
     */
    private void saveStart(String monadNo, String machineNo, String taskLx, String bqNo, String HJLX, String state, String mainId) {
        showWait();

        Communication.asyncRequest(new MainStartAffirm(monadNo, machineNo, taskLx, bqNo, HJLX, state, mainId), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                TipsDialogFragment.showNewInstance(this, getLayoutInflater().inflate(R.layout.callsys_tips_type_3, null), false);
                uiHandler.postDelayed(this::finish, 3000);
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }

        });
    }

    /**
     * 4.4. 查询数据字典
     */
    private void querySJZD(String SJZDID) {
        showWait();
        Communication.asyncRequest(new QueryDictData(SJZDID), r -> {
            stopWait();

            if (r instanceof OkResponse) {
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(((OkResponse) r).getData());
                    // 2018年9月25日 修改 保全开始页面是保全工操作 ，去数据字典的时候取“DATABQ”
                    JSONArray resultArrayBq = jsonObj.optJSONArray("DATABQ");
                    JSONArray resultArrayDc = jsonObj.optJSONArray("DATADC");
                    Gson gson = new Gson();
                    mTasksBq = gson.fromJson(resultArrayBq.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    mTasksDc = gson.fromJson(resultArrayDc.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());
                    mTasks.addAll(mTasksBq);
                    mTasks.addAll(mTasksDc);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, "查询数据字典失败！");
            }

        });
    }

    /**
     * 根据车号查询信息
     */
    private void queryMachineNoInfo(String machineNo) {
        showWait();

        Communication.asyncRequest(new QueryMachineNoInfo(machineNo), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                try {
                    JSONObject jsonObj = new JSONObject(((OkResponse) r).getData());
                    JSONObject data = jsonObj.optJSONObject("DATA");
                    if (data != null) {
                        isMonadNoCorrect = true;// 查询成功
                        mHJLX = "1";
                        binding.machineNoEt.removeTextChangedListener(machineNoEtWatcher);
                        binding.monadNoEt.removeTextChangedListener(monadNoEtWatcher);
                        mMonadNo = data.optString("MONADNO");
                        mMachineNo = data.optString("MACHINENO");
                        mBqNo = data.optString("BQNO");
                        mTaskLx = data.optString("TASKLX");
                        mState = data.optString("STATE");
                        mMainid = data.optString("MAINID");
                        binding.machineNoEt.setText(mMachineNo);
                        binding.monadNoEt.setText(mMonadNo);
                        binding.machineNoEt.addTextChangedListener(machineNoEtWatcher);
                        binding.monadNoEt.addTextChangedListener(monadNoEtWatcher);
                        if (!"null".equals(mBqNo)) {
                            binding.bqNoEt.setText(mBqNo);
                        }
                        initAllButton();
                        //如果是2   任务类型能改，保全工工号置灰
                        if ("2".equals(mState)) {
                            binding.bqNoEt.setEnabled(false);
                        }
                    } else {
                        SimpleDialog.show(this, "该三联单号还未开始保全！请重新输入！");
                    }

                } catch (JSONException e) {
                    SimpleDialog.show(this, "该三联单号还未开始保全！请重新输入！");
                }

            }

        });
    }


    private void initAllButton() {
        for (int i = 0; i < mTasks.size(); i++) {
            SJZDEntity task = mTasks.get(i);
            final Button button = new
                    Button(SaveStartActivity.this);

            LinearLayout.LayoutParams lp = new
                    LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(10, 0, 10, 0);// 设置边距
            button.setLayoutParams(lp);
            button.setText(task.SJXZ);
            button.setBackground(getDrawableCompat(R.drawable.btn_corner_gray));
            final int index = i;
            button.setOnClickListener(v -> {
                for (int j = 0; j < mTasks.size(); j++) {
                    Button button1 = (Button) binding.taskLayout.getChildAt(j);
                    button1.setBackground(getDrawableCompat(R.drawable.btn_corner_gray));
                }
                button.setBackground(getDrawableCompat(R.drawable.btn_corner_red));
                // 赋值任务类型
                mTaskLx = mTasks.get(index).KEYCODE;
            });


            button.setTextColor(getColor(R.color.white));
            button.setTextSize(30);

            if (mTaskLx != null && mTaskLx.equals(task.KEYCODE)) {
                button.setText(task.SJXZ);
                button.setBackground(getDrawableCompat(R.drawable.btn_corner_red));
                button.setTextColor(getColor(R.color.white));
            }
            binding.taskLayout.addView(button);
        }
    }


}
